package com.example.jt_sso.controller;

import com.example.jt_common.SysResult;
import com.example.jt_sso.pojo.Tbuser;
import com.example.jt_sso.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.List;

@Controller
public class UserController {

    @Autowired
    UserService userService;

    @RequestMapping("check/{param}/{type}")
    @ResponseBody
    public SysResult checkUserExist(@PathVariable("param") String param, @PathVariable("type") int type){
        boolean isExist = userService.checkUserExist(param,type);
        if (isExist){
            return SysResult.ok(true);
        }else {
            return SysResult.ok(false);
        }
    }

    /*
    * BindingResult为tbuser校验结果，校验规则在tbuser中
    * */

    @RequestMapping(name = "register",method= RequestMethod.POST)
    @ResponseBody
    public SysResult userRegister(@Valid Tbuser tbuser , BindingResult bindingResult){
        List<ObjectError> errors = bindingResult.getAllErrors();
        for (ObjectError error : errors) {
            System.out.println(error.getDefaultMessage());
        }

        //此处应该有加密、加盐、加密规则
        boolean isSuccess = userService.userRegister(tbuser);
        if (isSuccess){
            return SysResult.ok();
        }else {
            return SysResult.build(201,"注册失败");
        }
    }



    @RequestMapping(name = "login" , method = RequestMethod.POST)
    @ResponseBody
    public SysResult userLogin(String username,String password){
        String ticket = userService.userLogin(username,password);
        if (ticket!=null){
           return SysResult.ok(ticket);
        }else {
           return SysResult.build(201, "用户名、密码错误, 登录失败！");
        }
    }

    @RequestMapping(name = "ticketLogin")
    @ResponseBody
    public SysResult tickerLogin(String ticket){
        String jsonUser = userService.sessionLogin(ticket);
        if (jsonUser==null){
            return SysResult.build(201,"查询失败");
        }else {
            return SysResult.ok(jsonUser);
        }
    }

}
